﻿using System.Data;
using System.Text.RegularExpressions;
using OWASP.CodeReview.CodeCrawler.Engine;
using OWASP.CodeReview.CodeCrawler.Enums;

namespace CodeCrawler.UI.Engine.KeyPointersScan.ValidationSteps.Stage1 {
    /// <summary>
    /// Stage 1 : Use Regular Expressions to evaluate the presence of a threat within the current line of code
    ///           Likely to identify an high level of false positives.
    /// </summary>
    public static class Stage1 {

        public static Threat DeepSearch(DataRow threatInCatalog, string lineOfCode, int currentLineOfCode) {
            
            #region EXACT MATCH
            string deepSearchPattern = threatInCatalog[0].ToString().ToLower();
            var regex = new Regex(deepSearchPattern);

            // This is the easiest and lightest check at code level. The regular Expression will check for a specific pattern. 
            // Exact Match

            if(regex.IsMatch(lineOfCode.ToLower()))
            {
                var threatDiscovered = new Threat {Name = threatInCatalog[0].ToString()};

                if(!string.IsNullOrEmpty(threatDiscovered.Name))
                {
                    switch (int.Parse(threatInCatalog[1].ToString()))
                    {
                        case 1:
                            threatDiscovered.Level = ThreatLevel.Green;
                            break;

                        case 2:
                            threatDiscovered.Level = ThreatLevel.Yellow;
                            break;

                        case 3:
                            threatDiscovered.Level = ThreatLevel.Red;
                            break;
                    }
                }

                threatDiscovered.LineOfCode = currentLineOfCode;
                threatDiscovered.Description = threatInCatalog[2].ToString();
                threatDiscovered.OwaspGuideLines = threatInCatalog[4].ToString();
                return threatDiscovered;
            }
            #endregion

            return null;
        }
    }
}